package biz.ezcom.hibernate.test;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import biz.ezcom.hibernate.pojo.Component;
import biz.ezcom.hibernate.pojo.Employee;
import biz.ezcom.hibernate.pojo.User;

public class Client {
	@Test
	public void testSave(){
		Session session = null;
		Transaction tx = null;
		try{
			session = HibernateUtil.getSession();
			tx = session.beginTransaction();
			
			User user = new User();
			user.setName("Felix");
			Component componentA = new Component();
			componentA.setAddress("address_A");
			componentA.setEmail("user@ezcom.biz");
			user.setComponent(componentA);
			session.save(user);
			
			Employee employee = new Employee();
			employee.setName("EZCOM");
			Component componentB = new Component();
			componentB.setAddress("address_B");
			componentB.setEmail("employee@ezcom.biz");
			employee.setComponent(componentB);
			
			session.save(employee);
			tx.commit();
		}catch(Exception e){
			e.printStackTrace();
			tx.rollback();
		}finally{
			HibernateUtil.closeSession(session);
		}
	}
	
	@Test
	public void testGet(){
		Session session = null;
		Transaction tx = null;
		try{
			session = HibernateUtil.getSession();
			tx = session.beginTransaction();
			
			System.out.println("=======User=======================");
			User user = (User)session.get(User.class, 1);
			System.out.println("name: " + user.getName());
			Component componentA = user.getComponent();
			System.out.println("email: " + componentA.getEmail());
			System.out.println("address: " + componentA.getAddress());
			
			System.out.println("=======Employee=======================");
			Employee employee = (Employee)session.get(Employee.class, 1);
			System.out.println("name: " + employee.getName());
			Component componentB = employee.getComponent();
			System.out.println("email: " + componentB.getEmail());
			System.out.println("address: " + componentB.getAddress());
			
			tx.commit();
		}catch(Exception e){
			e.printStackTrace();
			tx.rollback();
		}finally{
			HibernateUtil.closeSession(session);
		}
	}
}
